<template>
  <el-dialog
    :visible="visible"
    :before-close="handleClose"
    :show-close="true"
    :close="handleClose"
    :append-to-body="true"
    class="normal-common-dialog-size update-account-dialog"
  >
    <SectionTitle title="待同步信息"/>
    <el-carousel
      v-loading="loading"
      v-if="accountUpdateList.length || loading"
      ref="carouselRef"
      :autoplay="false"
      :loop="false"
      height="516px"
      arrow="never"
      indicator-position="none"
      style="position: relative; max-height: calc(100vh - 120px);"
      @change="onCarouselChange"
    >
      <el-carousel-item v-for="updateInfo in accountUpdateList" :key="updateInfo.id" style="overflow: auto">
        <el-form
          :class="{'mobile-el-form': showMobilePage}"
          :label-position="showMobilePage?'left':'right'"
          style="padding-top: 16px;"
          label-width="80px"
          class="info-form">
          <el-row :gutter="10" :class="{'dividing': !showMobilePage}">
            <el-col :span="12">
              <el-form-item label="用户ID:">
                <ToolTip :content="updateInfo.code" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名:">
                <ToolTip :content="updateInfo.name" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template v-if="updateInfo.accountList.length">
          <DetailTabs v-model="activeTab" :tabs="updateInfo.accountList" placeholder="--" style="margin: 14px 0 18px" @tabClick="handleTabClick" />
          <div class="level-2">现资源信息</div>
          <el-form
            v-if="accountCompareData.oldInfo"
            :class="{'mobile-el-form': showMobilePage}"
            :label-position="showMobilePage?'left':'right'"
            type="flex"
            label-width="80px"
            class="info-form height55">
            <el-row :gutter="10" :class="{'dividing': !showMobilePage}">
              <el-col v-for="option in compareFormOptions" :key="'old_' + option.key" :span="12">
                <el-form-item :label="`${option.label}:`">
                  <div v-if="option.key === 'tag'" class="tag-wrap">
                    <div v-if="tagData.oldInfoTags.length" class="flex-center">
                      <div v-for="tag in tagData.oldInfoTags" :key="tag.id" class="tag-item ellipsisOne">
                        <ToolTip :content="tag.name" />
                      </div>
                      <el-popover
                        v-if="residueTagData.oldInfoTags.length"
                        placement="right"
                        width="240"
                        trigger="click">
                        <div class="tags-dialog-list">
                          <div v-for="tag in residueTagData.oldInfoTags" :key="tag.id" class="tag-item ellipsisOne">
                            <ToolTip :content="tag.name" />
                          </div>
                        </div>
                        <span slot="reference" class="tag-item pointer">+{{ residueTagData.oldInfoTags.length }}</span>
                      </el-popover>
                    </div>
                    <div v-else>--</div>
                  </div>
                  <ToolTip v-else-if="option.key === 'link'" :content="accountCompareData.oldInfo[option.key]" is-can-click @handelClick="openLink(accountCompareData.oldInfo[option.key])" />
                  <ToolTip v-else :content="accountCompareData.oldInfo[option.key]" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="level-2" style="margin-top: 10px">达人更新信息</div>
          <el-form
            v-if="accountCompareData.newInfo"
            :class="{'mobile-el-form': showMobilePage}"
            :label-position="showMobilePage?'left':'right'"
            type="flex"
            label-width="80px"
            class="info-form height55">
            <el-row :gutter="10" :class="{'dividing': !showMobilePage}">
              <el-col v-for="option in compareFormOptions" :key="'old_' + option.key" :span="12">
                <el-form-item :label="`${option.label}:`">
                  <div v-if="option.key === 'tag'" class="tag-wrap">
                    <div v-if="tagData.newInfoTags.length" class="flex-center">
                      <div v-for="tag in tagData.newInfoTags" :key="tag.id" :class="{'diff-tag': isDiffValue(accountCompareData, option.key)}" class="tag-item ellipsisOne">
                        <ToolTip :content="tag.name" />
                      </div>
                      <el-popover
                        v-if="residueTagData.newInfoTags.length"
                        placement="right"
                        width="240"
                        trigger="click">
                        <div class="tags-dialog-list">
                          <div v-for="tag in residueTagData.newInfoTags" :key="tag.id" :class="{'diff-tag': isDiffValue(accountCompareData, option.key)}" class="tag-item ellipsisOne">
                            <ToolTip :content="tag.name" />
                          </div>
                        </div>
                        <span slot="reference" :class="{'diff-tag': isDiffValue(accountCompareData, option.key)}" class="tag-item pointer">+{{ residueTagData.newInfoTags.length }}</span>
                      </el-popover>
                    </div>
                    <div v-else>--</div>
                  </div>
                  <ToolTip
                    v-else-if="option.key === 'link'"
                    :content="accountCompareData.newInfo[option.key]"
                    :class="{'diff-value': isDiffValue(accountCompareData, option.key)}"
                    is-can-click
                    @handelClick="openLink(accountCompareData.newInfo[option.key])" />
                  <ToolTip
                    v-else
                    :content="accountCompareData.newInfo[option.key]"
                    :class="{'diff-value': isDiffValue(accountCompareData, option.key)}"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="level-2 pending-header">
            待同步信息
            <el-button
              v-if="!getCurrApprovalStatus"
              type="primary"
              size="small"
              class="global-plain-btn edit-btn"
              @click="syncInfoDialogShow(accountCompareData.pendingInfo)">编辑</el-button>
          </div>
          <el-form
            v-if="accountCompareData.pendingInfo"
            :class="{'mobile-el-form': showMobilePage}"
            :label-position="showMobilePage?'left':'right'"
            type="flex"
            label-width="80px"
            class="info-form height55">
            <el-row :gutter="10" :class="{'dividing': !showMobilePage}">
              <el-col v-for="option in compareFormOptions" :key="'old_' + option.key" :span="12">
                <el-form-item :label="`${option.label}:`">
                  <div v-if="option.key === 'tag'" class="tag-wrap">
                    <div v-if="tagData.pendingInfoTags.length" class="flex-center">
                      <div v-for="tag in tagData.pendingInfoTags" :key="tag.id" :class="{'diff-tag': isDiffValue(accountCompareData, option.key, 'pendingInfo')}" class="tag-item ellipsisOne">
                        <ToolTip :content="tag.name" />
                      </div>
                      <el-popover
                        v-if="residueTagData.pendingInfoTags.length"
                        placement="right"
                        width="240"
                        trigger="click">
                        <div class="tags-dialog-list">
                          <div v-for="tag in residueTagData.pendingInfoTags" :key="tag.id" :class="{'diff-tag': isDiffValue(accountCompareData, option.key, 'pendingInfo')}" class="tag-item ellipsisOne">
                            <ToolTip :content="tag.name" />
                          </div>
                        </div>
                        <span slot="reference" :class="{'diff-tag': isDiffValue(accountCompareData, option.key, 'pendingInfo')}" class="tag-item pointer">+{{ residueTagData.pendingInfoTags.length }}</span>
                      </el-popover>
                    </div>
                    <div v-else>--</div>
                  </div>
                  <ToolTip
                    v-else-if="option.key === 'link'"
                    :content="accountCompareData.pendingInfo[option.key]"
                    :class="{'diff-value': isDiffValue(accountCompareData, option.key, 'pendingInfo')}"
                    is-can-click
                    @handelClick="openLink(accountCompareData.pendingInfo[option.key])" />
                  <ToolTip
                    v-else
                    :content="accountCompareData.pendingInfo[option.key]"
                    :class="{'diff-value': isDiffValue(accountCompareData, option.key, 'pendingInfo')}"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <img v-if="getCurrApprovalStatus" :src="getCurrApprovalStatus === 1 ? rejectIcon : passIcon" class="status-img" alt="">
        </template>
        <div v-else class="empty-account">
          <img :src="emptyImg" alt="">
          <div class="empty-text">当前用户没有可更新信息的账号</div>
        </div>
      </el-carousel-item>
    </el-carousel>
    <div v-if="accountUpdateList.length" class="footer-btns">
      <el-button :disabled="carouselIndex === 0" size="small" class="cut-btn" @click="toPrev">
        <i class="el-icon-arrow-left"/>
      </el-button>
      <transition name="el-fade-in-linear">
        <div v-show="accountUpdateList[carouselIndex].accountList.length && !getCurrApprovalStatus">
          <el-button :loading="approvalLoading" type="primary" size="small" @click="handleApproval(true)">通过</el-button>
          <el-button :loading="approvalLoading" type="danger" size="small" @click="handleApproval(false)">未过审</el-button>
        </div>
      </transition>
      <el-button :disabled="carouselIndex === accountUpdateList.length - 1" size="small" class="cut-btn" @click="toNext">
        <i class="el-icon-arrow-right"/>
      </el-button>
      <div class="pager-count">
        <span class="curr-count">{{ carouselIndex + 1 }}</span>/<span>{{ accountUpdateList.length }}</span>
      </div>
    </div>
    <EmptyPlaceholder
      v-else-if="!loading"
      :empty-img="emptyContentImg"
      :empty-text-top="10"
      style="margin: 30px 0;"
      text="暂无数据"
      image-size="140px"/>
    <AccountInfoSyncDialog ref="accountInfoSyncDialogRef" @infoSync="accountInfoSync" />
  </el-dialog>
</template>

<script>
import { mapState } from 'vuex';
import { getUpdateList, accountUpdate } from '@/api/flyUser';
import { isJSON, isObjEqual } from '@/utils/tools';
import SectionTitle from '@/components/Title';
import DetailTabs from '@/components/Common/baseComponent/DetailTabs';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import passIcon from '@/assets/customer/pass.png';
import rejectIcon from '@/assets/auditProcess/process_status_2.png';
import emptyImg from '@/assets/process_empty.png';
import emptyContentImg from '@/assets/empty-search.png';
import AccountInfoSyncDialog from './accountInfoSyncDialog';
export default {
  name: 'UpdateCheckDialog',
  components: { SectionTitle, DetailTabs, EmptyPlaceholder, AccountInfoSyncDialog },
  props: {
    ids: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      passIcon,
      rejectIcon,
      emptyImg,
      emptyContentImg,
      visible: false,
      loading: false,
      approvalLoading: false,
      carouselIndex: 0,
      activeTab: '',
      accountCompareData: {},
      accountUpdateList: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    compareFormOptions() {
      return [
        { label: '平台', key: 'platform' },
        { label: '账号ID', key: 'accountId' },
        { label: '账号名称', key: 'accountName' },
        // { label: '接单偏好', key: 'orderPreference' },
        { label: '粉丝量', key: 'fansNum' },
        { label: '链接', key: 'link' },
        { label: '标签', key: 'tag' }
      ];
    },
    getCurrApprovalStatus() {
      const currAccountData = this.accountUpdateList[this.carouselIndex] || {};
      let status = null;
      (currAccountData.accountList || []).forEach(item => {
        if (item.id === this.activeTab) {
          status = item.status;
        }
      });
      return status;
    },
    allPendingTags() {
      return this.getTags('pendingInfo');
    },
    allOldTags() {
      return this.getTags('oldInfo');
    },
    allNewTags() {
      return this.getTags('newInfo');
    },
    tagData() {
      return {
        pendingInfoTags: this.allPendingTags.length <= 3 ? this.allPendingTags : this.allPendingTags.slice(0, 2),
        oldInfoTags: this.allOldTags.length <= 3 ? this.allOldTags : this.allOldTags.slice(0, 2),
        newInfoTags: this.allNewTags.length <= 3 ? this.allNewTags : this.allNewTags.slice(0, 2)
      };
    },
    residueTagData() {
      return {
        pendingInfoTags: this.allPendingTags.length <= 3 ? [] : this.allPendingTags.slice(2),
        oldInfoTags: this.allOldTags.length <= 3 ? [] : this.allOldTags.slice(2),
        newInfoTags: this.allNewTags.length <= 3 ? [] : this.allNewTags.slice(2)
      };
    }
  },
  methods: {
    openDialog(ids) {
      this.visible = true;
      this.initList(ids);
      this.loading = true;
    },
    initList(ids) {
      this.loading = true;
      getUpdateList({ ids }).then(res => {
        if (res.code === 200) {
          this.accountUpdateList = res.data || [];
          this.accountUpdateList.forEach(item => { // 初始待同步信息默认与博主更新信息一致
            if (Array.isArray(item.accountList) && item.accountList.length) {
              item.accountList.forEach(account => {
                this.$set(account, 'pendingInfo', _.cloneDeep(account.newInfo));
              });
            }
          });
          this.$nextTick(() => {
            this.onCarouselChange(0);
          });
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    toPrev() {
      this.activeTab = null;
      this.$refs['carouselRef'].prev();
    },
    toNext() {
      this.activeTab = null;
      this.$refs['carouselRef'].next();
    },
    onCarouselChange(index) {
      this.carouselIndex = index;
      const currUpdateData = this.accountUpdateList[index];
      if (currUpdateData.accountList.length) {
        // 切换审批后默认显示首个待审批的账号
        for (let i = 0; i < currUpdateData.accountList.length; i++) {
          if (!currUpdateData.accountList[i].status) {
            this.activeTab = currUpdateData.accountList[i].id;
            this.accountCompareData = currUpdateData.accountList[i];
            break;
          } else if (i === currUpdateData.accountList.length - 1) {
            this.activeTab = currUpdateData.accountList[0].id;
            this.accountCompareData = currUpdateData.accountList[0];
          }
        }
      }
    },
    handleTabClick(id) {
      this.activeTab = id;
      const currUpdateData = this.accountUpdateList[this.carouselIndex];
      this.accountCompareData = currUpdateData.accountList.find(i => i.id === id);
    },
    isDiffValue(data, key, newInfoKey = 'newInfo') {
      if (key === 'tag') {
        const oldTagArr = isJSON(data.oldInfo[key]) ? JSON.parse(data.oldInfo[key]) : [];
        const newTagArr = isJSON(data[newInfoKey][key]) ? JSON.parse(data[newInfoKey][key]) : [];
        return !isObjEqual(oldTagArr, newTagArr);
      }
      return data.oldInfo[key] !== data[newInfoKey][key];
    },
    getTags(key) {
      if (this.accountCompareData && this.accountCompareData[key] && this.accountCompareData[key].tag) {
        return isJSON(this.accountCompareData[key].tag) ? JSON.parse(this.accountCompareData[key].tag) : [];
      }
      return [];
    },
    openLink(val) {
      if (/^(www)/i.test(val)) {
        val = `https://${val}`;
        window.open(val);
        return;
      } else if (val && this.testUrl(val)) {
        window.open(val);
        return;
      }
      this.$message.warning('无效的链接');
    },
    testUrl(url) {
      const reg = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
      return !!reg.test(url);
    },
    checkAccount(accountInfo) {
      const currAccountOldInfo = accountInfo.oldInfo || {};
      return Object.keys(currAccountOldInfo).every(key => currAccountOldInfo[key] === null);
    },
    handleApproval(isPass) {
      this.approvalLoading = true;
      const currAccountData = this.accountUpdateList[this.carouselIndex] || {};
      if (isPass) {
        const accountInfo = currAccountData.accountList.find(item => item.id === this.activeTab);
        const isNewAccountName = this.checkAccount(accountInfo);
        if (isNewAccountName) {
          this.$message.error(`账号【${accountInfo.newInfo.accountName}】不存在或关联了其他供应商`);
          this.approvalLoading = false;
          return;
        }
        const { fansNum, link, tag, platformId, accountName } = accountInfo.pendingInfo;
        const params = {
          id: currAccountData.id,
          accountCode: accountInfo.id,
          tag: isJSON(tag) ? JSON.parse(tag) : [],
          accountName,
          platformId,
          fansNum,
          link
        };
        accountUpdate(params).then(res => {
          if (res.code === 200) {
            currAccountData.accountList.forEach(item => {
              if (item.id === this.activeTab) {
                this.$set(item, 'status', 2);
              }
            });
          }
          this.switchNextApprovalTab();
          this.approvalLoading = false;
        }).catch(err => {
          console.log(err);
          this.approvalLoading = false;
        });
      } else {
        currAccountData.accountList.forEach(item => {
          if (item.id === this.activeTab) {
            this.$set(item, 'status', 1);
          }
        });
        this.switchNextApprovalTab();
        this.approvalLoading = false;
      }
    },
    switchNextApprovalTab() {
      const currAccountData = this.accountUpdateList[this.carouselIndex] || {};
      /**
       * 自动跳转下一个规则
       * ABC三个审批，AC均未审批，审批完B之后跳至C，审批完C之后再跳至A
       * */
      let beforeNextTab = '';
      let afterNextTab = '';
      const findCurrTabIndex = currAccountData.accountList.findIndex(account => account.id === this.activeTab);
      for (let i = 0; i < currAccountData.accountList.length; i++) {
        const notApproval = !currAccountData.accountList[i].status; // 未审批
        if (notApproval) {
          if (findCurrTabIndex > i) {
            beforeNextTab = currAccountData.accountList[i].id;
          } else {
            afterNextTab = currAccountData.accountList[i].id;
            break;
          }
        }
      }
      if (afterNextTab || beforeNextTab) {
        this.handleTabClick(afterNextTab || beforeNextTab);
      }
    },
    syncInfoDialogShow(data) {
      const initData = _.cloneDeep(data);
      initData.tag = isJSON(initData.tag) ? JSON.parse(initData.tag) : [];
      this.$refs['accountInfoSyncDialogRef'].initDialog(initData);
    },
    accountInfoSync(data) {
      const currAccountData = this.accountUpdateList[this.carouselIndex];
      currAccountData.accountList.forEach(item => {
        if (item.id === this.activeTab) {
          data.tag = JSON.stringify(data.tag);
          item.pendingInfo = data;
        }
      });
    },
    handleClose() {
      this.activeTab = null;
      this.accountUpdateList = [];
      this.$emit('close');
      this.visible = false;
      this.approvalLoading = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.update-account-dialog {
  &::v-deep {
    .el-tabs__nav-prev, .el-tabs__nav-next {
      line-height: 32px !important;
    }
    .el-dialog__body {
      min-height: 300px;
    }
  }
  .level-2 {
    font-weight: bold;
    color: #333;
    margin-bottom: 4px;
    &::before {
      position: relative;
      content: '';
      width: 3px;
      height: 3px;
      display: inline-block;
      background-color: #406EFF;
      vertical-align: bottom;
      top: -8px;
      margin-right: 6px;
    }
  }
  .tag-wrap{
    display: flex;
    align-items: center;
    height: 32px;
    .tags-dialog-list {
      display: flex;
      flex-wrap: wrap;
      @include scrollBar($x: hidden, $y: auto, $width: 3px);
      max-height: 200px;
      .tag-item {
        margin-bottom: 5px;
      }
    }
    &::v-deep {
      .el-popover__reference-wrapper {
        display: flex;
      }
    }
  }
  .diff-value {
    color: #FF3333 !important;
    &::v-deep {
      .is-can-click {
        color: #FF3333 !important;
      }
    }
  }
  .status-img {
    position: absolute;
    top: 110px;
    right: 0;
    width: 80px;
    z-index: 2;
  }
  .pending-header {
    margin-top: 10px;
    position: relative;
    .edit-btn {
      position: absolute;
      right: 0;
      top: -3px;
    }
  }
  .empty-account {
    text-align: center;
    margin-top: 100px;
    img {
      width: 120px;
      height: 118px;
    }
    .empty-text {
      color: #333;
      font-size: 16px;
      font-weight: bold;
      margin-top: 12px;
    }
  }
  .footer-btns {
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: relative;
    .cut-btn {
      width: 32px;
      height: 32px;
      padding: 0;
    }
    .pager-count {
      position: absolute;
      bottom: 0;
      right: 48px;
      font-size: 14px;
      color: #999;
      font-family: Alibaba PuHuiTi, Alibaba PuHuiTi-Bold;
      .curr-count {
        font-weight: bold;
        color: #333;
      }
    }
  }
}
.tag-item{
  display: inline-block;
  max-width: 100px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color:#406EFF;
  font-size: 12px;
  padding: 0 8px;
  background: #eff4ff;
  border-radius: 10px;
  margin-right: 4px;
  height: 20px;
  line-height: 20px;
}
.diff-tag {
  background-color: #FFEAF4;
  color: #FF3333;
}
.info-form {
  & ::v-deep {
    .el-form-item {
      margin-bottom: 0;
      .el-form-item__label {
        font-size: 14px;
        font-weight: 400;
        color: #999999 !important;
        opacity: 1;
        line-height: 30px;
      }
    }
    .el-form-item__content {
      font-size: 14px;
      line-height: 30px;
      font-weight: 400;
      color: #333333;
      opacity: 1;
    }
  }
}
.dividing {
  &::v-deep {
    .el-col {
      .el-form-item__content {
        border-right: 1px solid #EBEEFD;
      }
      &:nth-child(2n) {
        .el-form-item__content {
          border-right: none;
        }
      }
      &:last-child {
        .el-form-item__content {
          border-right: none;
        }
      }
    }
  }
}
</style>
